<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useAtlasStore } from '@/store/modules/atlas';
import { searchData } from '@/api/search';
import { getClassify } from '@/api/earlyWarning';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import componentsTitle from '@/constants/components/componentsTitle';
import { MapSiteEnums } from '@/enums/siteEnums';
import { MapDeviceTypes } from '@/enums/MapDeviceTypesEnum';
import { getAlarmTypeCode } from '@/enums/AlarmTypeEnum';
import COMPONENT_TITLES from '@/constants/components/componentsTitle';
import { useGasSearchStore } from '@/store/modules/earlyWarning/useGasSearchStore';

const useGasSearch = useGasSearchStore();
const { addPoint, getEntityById, createPopUp } = useCesiumPoints();
const atlasStore = useAtlasStore();
const { atlasChange } = atlasStore;
const form = reactive({
  type: '',
  str: '',
  pageNum: 1,
  pageSize: 10,
  category: ''
});
const isActive = ref<string[]>([]);
const filtering = ref(false);
const options = [
  {
    value: 'SITE',
    label: '站点'
  },
  {
    value: 'MONITOR',
    label: '监测设备'
  },
  {
    value: 'GAOJINGTYPE',
    label: '报警'
  },
  {
    value: 'WARING',
    label: '预警'
  },
  {
    value: 'REPAIR',
    label: '抢修队'
  },
  {
    value: 'VIDEO',
    label: '视频'
  }
];

const detailData = ref<any[]>([]);
const loading = ref(false);
const formRef = ref();
const total = ref(0);
const noMore = computed(() => detailData.value.length >= total.value);
const category = ref([]);
const handleEnter = async () => {
  try {
    formRef.value.validate((res: any) => {
      if (res) {
        loading.value = true;
        form.pageNum = 1;
        detailData.value = [];
        if (!form.type) {
          ElMessage({ message: '请选择设备类型', type: 'warning' });
          return;
        }
        searchData(form)
          .then((res) => {
            detailData.value = res.data.rows;
            total.value = res.data.total;
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  } catch (error) {
    loading.value = false;
  }
};

const loadMore = async () => {
  if (loading.value || noMore.value) return;

  try {
    loading.value = true;
    form.pageNum += 1;
    const res = await searchData(form);
    detailData.value = [...detailData.value, ...res.data.rows];
    total.value = res.data.total;
  } catch (error) {
    console.error('加载更多数据失败:', error);
  } finally {
    loading.value = false;
  }
};

const advancedFiltering = async () => {
  filtering.value = !filtering.value;
  deletePoint();
  if (filtering.value) {
    const { data } = await getClassify();
    filteringData.value = data;
  }
};

const deletePoint = () => {
  detailData.value = [];
  reset();
  useGasSearch.initPoints();
};
//处理数据 返回地图点位所需要的参数
const processingData = (item: any) => {
  console.log('item', item);
  const processingCompleteObj = {
    name: undefined,
    modelTitle: undefined
  };
  switch (form.type) {
    case 'SITE':
      processingCompleteObj.name = MapSiteEnums(item.type);
      processingCompleteObj.modelTitle = componentsTitle.SITE_INFO;
      break;
    case 'MONITOR':
      processingCompleteObj.name = item.monitorScenceName;
      processingCompleteObj.modelTitle = MapDeviceTypes(item.monitorType);
      break;
    case 'GAOJINGTYPE':
      processingCompleteObj.name = getAlarmTypeCode(item.alarmType);
      processingCompleteObj.modelTitle = componentsTitle.ALARM_TYPE;
      break;
    case 'WARING':
      processingCompleteObj.name = item.alarmTypeName;
      processingCompleteObj.modelTitle = componentsTitle.ALERT_OVERVIEW;
      break;
    case 'REPAIR':
      processingCompleteObj.name = COMPONENT_TITLES.REPAIR_TEAM;
      processingCompleteObj.modelTitle = COMPONENT_TITLES.REPAIR_TEAM;
      break;
    case 'VIDEO':
      processingCompleteObj.name = COMPONENT_TITLES.REAL_TIME_MONITORING;
      processingCompleteObj.modelTitle = COMPONENT_TITLES.REAL_TIME_MONITORING;
      break;
  }
  return processingCompleteObj;
};
const postMapData = (item: any) => {
  const { name, modelTitle } = processingData(item);
  useGasSearch.dataSource.push(addPoint(item, name, modelTitle));
  const entity = getEntityById(item.id);
  createPopUp(entity);
};

const filteringHandler = (value: any) => {
  if (isActive.value.includes(value)) {
    isActive.value.splice(isActive.value.indexOf(value), 1);
  } else {
    isActive.value.push(value);
  }
  let flag = true;
  category.value.forEach((item, index) => {
    if (item == value) {
      category.value.splice(index, 1);
      flag = false;
    }
  });
  if (flag) {
    category.value.push(value);
  }
  form.category = category.value.join(',');
  form.type = 'MONITOR';
  handleEnter();
};
const getDisplayText = (item: any) => {
  if (item.name) return item.name;
  if (item.instPos) return item.instPos;
  if (item.alarmCode && item.alarmAddr) return `【${item.alarmCode}】${item.alarmAddr}`;
  if (item.occurrenceAddress) return item.occurrenceAddress;
  return '无数据';
};

const filteringData = ref([]);
const reset = () => {
  form.type = '';
  form.str = '';
  form.pageNum = 1;
  form.pageSize = 10;
  form.category = '';
};
</script>

<template>
  <div class="search-main">
    <div class="layer-title">
      <div class="title">点位查询</div>
      <el-icon class="close-icon" @click="atlasChange('search')">
        <Close />
      </el-icon>
    </div>
    <el-form ref="formRef" :model="form">
      <el-row type="flex" justify="space-between">
        <el-col :span="11">
          <el-select
            v-model="form.type"
            :teleported="false"
            clearable
            placeholder="请选择搜索类型"
            class="select_box"
            popper-class="select-popper"
            :popper-append-to-body="false"
          >
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
        <el-col :span="11">
          <el-input placeholder="请输入关键词" v-model="form.str" class="input_box" @keyup.enter="handleEnter">
            <template #prefix>
              <el-icon class="el-input__icon" @click="handleEnter">
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-form>
    <div class="station-module">
      <div class="station-module-main">
        <div class="sousuojieguo-box">
          <div>搜索结果</div>
          <div>
            <svg-icon icon-class="shaixuan" style="fill: currentColor; cursor: pointer" @click="advancedFiltering" />
            <el-icon class="delete-box" @click="deletePoint">
              <Delete />
            </el-icon>
          </div>
        </div>
        <div class="filtering-box" v-if="filtering">
          <h1>标签</h1>
          <div class="button-box">
            <div
              class="button"
              :class="{ isActive: isActive.includes(item) }"
              v-for="(item, index) in filteringData"
              :key="index"
              @click="filteringHandler(item)"
            >
              {{ item }}
            </div>
          </div>
        </div>
        <div>
          <div v-if="detailData.length === 0 && !loading" class="empty-text">暂无数据</div>
          <div v-else v-infinite-scroll="loadMore" :infinite-scroll-disabled="loading || noMore" class="list">
            <div class="station-item" v-for="(item, index) in detailData" :key="index">
              <div class="station-item-font-box" @click="postMapData(item)">
                {{ getDisplayText(item) }}
              </div>
              <div class="station-item-left"></div>
            </div>
            <div v-if="loading" class="loading-text">加载中...</div>
            <div v-if="noMore && detailData.length > 0" class="no-more-text">没有更多数据了</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.search-main {
  padding: 20px;
  box-sizing: border-box;
  z-index: 99;
  color: #fff;
  background-color: rgba($color: #004068, $alpha: 0.6);
  width: 20rem;
  max-height: 81.7%;
  border: 2px solid #045bbd;
  box-shadow: inset 0 0 25px 0 #1b5bfb;

  .layer-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    margin-bottom: 10px;

    .title {
      font-family: PangMenZhengDao;
      font-size: 1.125rem;
    }

    .close-icon {
      cursor: pointer;
    }

    .title:before {
      content: '';
      display: inline-block;
      width: 0.375rem;
      height: 1rem;
      margin-right: 0.25rem;
      background-color: #3ba0ff;
      vertical-align: text-top;
    }
  }

  .station-module {
    position: relative;
    width: 100%;
    margin-top: 10px;
  }

  .station-module-main {
    padding: 0.9375rem;
    box-sizing: border-box;
    width: 100%;
    max-height: 40rem;
    background-color: rgba(6, 48, 68, 0.3);
    overflow: auto;

    .sousuojieguo-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #24f2fe;
      padding: 4px 0;
      box-sizing: border-box;
      border-bottom: 1px solid #00ffff;

      div {
        .delete-box {
          cursor: pointer;
          color: #fff;
          margin-left: 4px;
        }
      }
    }

    .filtering-box {
      width: 100%;
      padding: 6px;
      box-sizing: border-box;
      height: 200px;
      overflow: auto;

      h1 {
        color: #24f2fe;
        font-size: 18px;
        font-weight: 800;
        margin-bottom: 4px;
      }

      .button-box {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;

        .button {
          min-width: 80px;
          height: 30px;
          line-height: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          background: transparent;
          border: 1px solid #0673f0;
          text-align: center;
          box-sizing: border-box;
          outline: none;
          font-weight: 500;
          padding: 12px 20px;
          font-size: 14px;
          border-radius: 4px;
          margin-left: 4px;
          margin-bottom: 4px;
          box-shadow: inset 0 0 0.625rem 0 #045bbd;
        }

        .isActive {
          color: #fff;
          background-color: #409eff;
          box-shadow: inset 0 0 0.625rem 0 #409eff;
          border: 1px solid #409eff;
        }
      }
    }

    .list {
      min-height: 100px;
    }

    .station-item {
      position: relative;
      width: 100%;
      min-height: 1.875rem;
      background: rgba(14, 89, 214, 0.34);
      margin-top: 0.625rem;
      line-height: 1.875rem;
      padding-left: 1.25rem;
      box-sizing: border-box;
      font-size: 1.125rem;
      display: flex;
      justify-content: space-between;
      cursor: pointer;

      .station-item-font-box {
        color: #fff;
      }

      .value-label {
        padding-right: 0.625rem;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
      }

      .station-item-left {
        position: absolute;
        width: 0.25rem;
        height: 100%;
        background-color: #43ff8b;
        left: 0;
        top: 0;
      }
    }

    .loading-text,
    .no-more-text,
    .empty-text {
      text-align: center;
      padding: 10px;
      color: #ccc;
      font-size: 14px;
    }
  }
}

.input_box {
  // 默认状态样式更改
  height: 30px;

  :deep(.el-input__wrapper) {
    background-color: rgba(30, 109, 235, 0.2) !important;
    border-color: transparent !important;
    box-shadow: inset 0 0 8px 0 rgba(4, 91, 189, 0.6) !important;
  }

  :deep(.el-input__wrapper.is-focus) {
    border-color: transparent !important;
    box-shadow: inset 0 0 8px 0 rgba(4, 91, 189, 0.6) !important;
  }

  :deep(.el-input__wrapper:hover) {
    border-color: transparent !important;
  }

  /* 只更改具有.el-input类名的元素的占位符文本样式 */
  :deep(.el-input__inner::placeholder) {
    font-size: 14px;
    font-weight: 500;
    color: white;
    opacity: 0.6;
  }

  // 清除按钮
  :deep(.el-input__clear) {
    color: white !important;
  }

  :deep(.el-input__inner) {
    color: white !important; // 字体色
  }

  // 确保input背景色
  :deep(.el-input) {
    background-color: rgba(30, 109, 235, 0.2) !important;
  }
}

.select_box {
  :deep(.el-select__wrapper) {
    background-color: rgba(30, 109, 235, 0.2) !important;
    box-shadow: inset 0 0 8px 0 rgba(4, 91, 189, 0.6) !important;
    border: none !important;
  }

  :deep(.el-select__wrapper.is-focus) {
    border-color: transparent !important;
    box-shadow: inset 0 0 8px 0 rgba(4, 91, 189, 0.6) !important;
  }

  :deep(.el-select__wrapper:hover) {
    border-color: transparent !important;
  }

  :deep(.el-input__inner) {
    color: white !important; // 字体色
  }

  :deep(.el-select__placeholder) {
    color: white !important;
    opacity: 0.9;
  }

  // 确保下拉框背景色
  :deep(.el-select) {
    background-color: rgba(30, 109, 235, 0.2) !important;
  }
}
</style>
